<?php
declare(strict_types=1);

namespace Zlf\Mysql;

use PDO;
use Zlf\Mysql\Traits\{Config, DataOperator, Mysql, Transaction};

class Database
{
    use Config;
    use Transaction;
    use DataOperator;
    use Mysql;

    /**
     * @var ?Pdo 数据库连接实例
     */
    private ?Pdo $connect = null;

    public function __construct(
        private string $host,//数据库地址
        private string $dbname,//数据库名称
        private string $user,//账号
        private string $pass,//密码
        private int    $port = 3306,//端口
        private string $charset = 'utf8mb4'//编码
    )
    {

    }


    /**
     * @describe 初始化数据实例
     * @param string $host
     * @param string $db
     * @param string $user
     * @param string $pass
     * @param int $port
     * @param string $charset
     * @return Database
     * @user zlf zms-pro@qq.com 2025/1/17
     */
    public static function Instance(
        string $host,//数据库地址
        string $db,//数据库名称
        string $user,//账号
        string $pass,//密码
        int    $port = 3306,//端口
        string $charset = 'utf8mb4'//编码
    ): Database
    {
        return new self($host, $db, $user, $pass, $port, $charset);
    }


    /**
     * @describe 获取数据库实例
     * @return PDO
     * @user zlf zms-pro@qq.com 2025/1/18
     */
    public function connect(): PDO
    {
        if ($this->connect instanceof PDO) {
            return $this->connect;
        }
        $this->connect = new PDO(
            "mysql:host={$this->host};port={$this->port};dbname={$this->dbname};charset={$this->charset}",
            $this->user,
            $this->pass,
            [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,//设置错误报告模式
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,//设定默认的fetch模式
                PDO::ATTR_AUTOCOMMIT => false,//设置自动提交模式
                PDO::ATTR_EMULATE_PREPARES => false,//启用/禁用模拟预处理语句
                PDO::ATTR_TIMEOUT => 60,//超时时间
                PDO::ATTR_PERSISTENT => true,//设置持久连接
                PDO::ATTR_CASE => PDO::CASE_NATURAL,//定义列名大小写处理方式
            ]
        );
        return $this->connect;
    }

    /**
     * 销毁时关闭数据库连接
     */
    public function __destruct()
    {
        $this->close();
    }

    /**
     * @describe 关闭连接
     * @return void
     * @user zlf zms-pro@qq.com 2025/1/18
     */
    public function close(): void
    {
        $this->connect = null;
    }
}